import { feedApi } from '/api/feed'
import { GlobalData } from '/store/state'
import { checkAuth } from '/store/actions'
import { $event, $logger, $utils } from '/utils'
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import getMessage from 'ts-msg-handler'

const defaultInputPlaceholder = '随便说说~'

Page({
  data: {
    isFullScreen: GlobalData.isFullScreen,
    commentId: 0,
    replys: [] as any,
    comment: {} as DomoComment,

    limit: 20,
    nomore: false,
    commentFocus: false,
    inputValue: '',
    inputPlaceholder: defaultInputPlaceholder,
    replyUser: 0,
    comment_id: 0, // 一级评论ID
    reply_id: 0, // 被回复评论ID
    /** 键盘弹起高度 */
    keyboardOffsetTop: 0,

    loading: true,
    access: {},
  },
  async onLoad(Options) {
    this.setData({
      isFullScreen: GlobalData.isFullScreen,
    })
    // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
    // @ts-ignore
    const commentId = parseInt(Options.id)
    try {
      if (!commentId) throw new Error('该评论不存在或已被删除')

      this.setData({ commentId, comment_id: commentId, reply_id: commentId })
      await this.getReplys()
      this.setData({ loading: false })
    } catch (error) {
      console.log(error)
      $logger.debug('回复详情加载失败', { query: Options, error })
      wx.navigateBack({ delta: 1 })
    }
  },
  async onShow() {
    this.getPosition()
    $event.on('after:boot', this, () => {
      this.getPosition()
    })
    await checkAuth()
  },
  async onPullDownRefresh() {
    this.setData({ nomore: false })
    await this.getReplys()
    wx.stopPullDownRefresh()
  },
  async onReachBottom() {
    this.getReplys(true)
  },
  getPosition() {
    this.setData({
      access: GlobalData.access,
      navigationHeight: GlobalData.navigationHeight,
    })
  },
  async getReplys(more = false) {
    const { replys: _replys, limit, nomore } = this.data
    if (nomore) {
      return wx.showToast({ title: '没有更多了', icon: 'none' })
    }
    wx.showLoading({ title: '加载中' })
    try {
      const params = {
        limit,
        after: more && _replys.length ? _replys[_replys.length - 1].id : 0,
      }
      const { replys, comment } = await feedApi.getCommentReplys(this.data.commentId, params)

      this.setData({
        comment,
        // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
        // @ts-ignore
        replys: more ? [..._replys, ...replys] : replys,
        // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
        // @ts-ignore
        nomore: replys.length < limit,
      })
      wx.hideLoading()
    } catch (error) {
      wx.hideLoading()
      wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
    }
    return
  },
  async onCommentConfirm(event: any) {
    const content: string = event.detail.value
    const { replyUser, comment_id, reply_id } = this.data
    const payload: PostCommentBody = { body: content }
    /*
    对动态进行一级评论参数：body
    对动态的一级评论进行评论(二级评论)参数：body、reply_user(回复用户)、reply_id(一级评论id)、pid(一级评论id)
    对动态的二级评论进行回复(二级评论的回复)参数：body、reply_user(回复用户)、pid(一级评论id)、reply_id(二级评论id)
     */
    if (replyUser) payload.reply_user = replyUser
    if (comment_id) payload.pid = comment_id
    if (reply_id) payload.reply_id = reply_id
    try {
      const { comment, amount } = await feedApi.postFeedComment(
        this.data.comment.commentable_id,
        payload,
      )
      if (amount) {
        $event.emit('showMessage', {
          message: '回复成功',
          amount: amount,
        } as GetRewardMessageReturns)
      } else {
        wx.showToast({
          title: '回复成功',
          icon: 'success',
          duration: 2000,
        })
      }
      let replys = this.data.replys as any
      replys = [comment, ...this.data.replys]
      this.setData({
        // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
        // @ts-ignore
        'comment.reply_count': this.data.comment.reply_count + 1,
        replys,
        inputValue: '',
        inputFocus: false,
        replyUser: null as any,
        comment_id: this.data.commentId,
        reply_id: this.data.commentId,
      })
      // $event.emit('showComment', { feedId: +this.data.feed.id })
    } catch (error) {
      wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
    }
  },
  async onCommentFocus() {
    await checkAuth()
  },
  bindkeyboardheightchange(event: WechatMiniprogram.TouchEvent) {
    // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
    //@ts-ignore
    this.handleKeyboard(this, event)
  },
  handleKeyboard: $utils.throttle((that, event: WechatMiniprogram.TouchEvent) => {
    const { height } = event.detail
    if (height != that.data.keyboardOffsetTop) {
      that.setData({
        commentFocus: true,
        keyboardOffsetTop: height,
      })
    }
  }, 100),
  onCommentBlur() {
    this.setData({
      commentFocus: false,
      keyboardOffsetTop: 0,
      inputPlaceholder: defaultInputPlaceholder,
    })
  },
  onReply(event: WechatMiniprogram.BaseEvent) {
    const { comment } = this.data
    const { reply = {} } = event.currentTarget.dataset
    if (GlobalData.logged!.id === reply.user_id) {
      wx.showActionSheet({
        itemList: ['删除回复'],
        success: async ({ tapIndex }) => {
          if (tapIndex === 0) {
            wx.showLoading({ title: '删除中' })
            try {
              await feedApi.deleteFeedComment(comment.commentable_id, reply.id)

              wx.hideLoading()
              let newList = this.data.replys
              newList = newList.filter((item: DomoComment) => item.id !== reply.id)
              // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
              // @ts-ignore
              comment.reply_count -= 1
              this.setData({
                comment,
                replys: newList,
              })
            } catch (error) {
              wx.hideLoading()
              // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
              //@ts-ignore
              wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
            }
          }
        },
      })
    } else {
      this.setData({
        replyUser: reply.user.id,
        comment_id: comment.id,
        reply_id: reply.id,
        inputPlaceholder: `回复 ${reply.user.name}:`,
        commentFocus: true,
      })
    }
  },
  async onReport(event: WechatMiniprogram.BaseEvent) {
    const { reply = {} } = event.currentTarget.dataset
    await checkAuth()
    if (GlobalData.logged!.id === reply.user_id) return
    wx.navigateTo({
      url: `/pages/report/report?type=comment&id=${reply.id}`,
    })
  },
})
